package com.leagueoflegends.controller;

import com.leagueoflegends.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@Controller
public class UploadController {

    @Autowired
    UploadService uploadService;

    /**
     * 上传图片接口
     * @param files 前端传过来的图片
     * @param catalog 图片的对应文件夹
     * @return COS 图片地址列表
     *  /uploads/champion 英雄
     *  /uploads/passive 被动
     *  /uploads/spell 主动技能
     *  /uploads/skin/loading 载入图片
     *  /uploads/skin/splash 原画
     *  /uploads/skin/tiles 皮肤小头像
     */
    @CrossOrigin
    @ResponseBody
    @PostMapping("/uploads/{catalog}")
    public List<String> uploadfile(@RequestParam("files") MultipartFile[] files, @PathVariable String catalog) throws Exception {

        if (files.length == 0) {
            return null;
        }

        List<String> fileList  = new ArrayList<>();
        String COSpath = "https://hello-world-1302823106.cos.ap-nanjing.myqcloud.com/";

//        System.out.println(files);

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            File file1 = multipartFileToFile(file);
            String s = uploadService.uploadfile(file1, catalog);
            fileList.add(COSpath + s);
            System.out.println(COSpath + s);
        }

        return fileList;
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

}
